import {DetailItem, ReportDetail} from "../../../type/entity/ReportDetail";
import {StatePagingType} from "../index";
import RequestStatus from "../RequestStatus";
import {createAsyncThunk, createSlice, PayloadAction} from "@reduxjs/toolkit";

import RequestHandler from "../../../http/RequestHandler";
import {AMOUNT_ACCURACY} from "../../../util/Constant";

/**
 * 报销记录详细信息redux数据类型
 */
export type ReportDetailState = StatePagingType<ReportDetail> & {
    /**
     * 报销记录总金额,这个总金额为每次总服务器获取列表后在redux中计算金额
     */
    totalMoney: number,
    reportId?: number,
    /**
     * 报销项目列表
     */
    detailItems: DetailItem[],
    defaultItem?: string,
}


/**
 * 根据报销单编号获取报销单的详细信息列表
 */
export const fetchReportDetailList = createAsyncThunk(
    'reportDetail/fetchReportDetailList',
    async (reportId: number) => {
        return await RequestHandler.get<ReportDetail[]>(`/record/report/detail/list/${reportId}`);
    }
);
/**
 * 添加报销单详细信息,如果添加成功,反回新的详细对象
 */
export const fetchAddReportDetail = createAsyncThunk(
    'reportDetail/fetchAddReportDetail',
    async (reportDetail: ReportDetail) => {
        return await RequestHandler.put<ReportDetail>("/record/report/detail/return", reportDetail);
    }
);

/**
 * 更新报销单
 */
export const fetchUpdateReportDetail = createAsyncThunk(
    'reportDetail/fetchUpdateReportDetail',
    async (reportDetail: ReportDetail): Promise<{success: boolean, detail: ReportDetail, msg: string}> => {
        const res = await RequestHandler.post<number>("/record/report/detail", reportDetail);
        return {
            success: res.success,
            detail: reportDetail,
            msg: res.message + res.data
        };
    }
);

/**
 * 获取报销项目列表
 */
export const fetchDetailItemList = createAsyncThunk(
    'reportDetail/fetchDetailItemList',
    async () => await RequestHandler.get<DetailItem[]>("/record/report/detail/item")
);
/**
 * 删除报销项目
 */
export const fetchRemoveItem = createAsyncThunk(
    'reportDetail/fetchRemoveItem',
    async (key: string) => {
        const res = await RequestHandler.delete<boolean>("/record/report/detail/item/" + key);
        return res.success ? key : "";
    }
);


/** 状态初始化数据 */
const initialState: ReportDetailState = {
    data: [],
    loading: false,
    requestStatus: RequestStatus.INIT,
    totalMoney: 0,
    currentPage: 0,
    pageSize: 0,
    total: 0,
    totalPage: 0,
    detailItems: []
};
export const reportDetailSlice = createSlice({
    name: 'reportDetail',
    initialState,
    reducers: {
        /**
         * 更新报销单id
         * @param state
         * @param action
         */
        updateReportId: (state, action: PayloadAction<number>) => {
            state.reportId = action.payload;
        },
        /**
         * 更新报销单详细信息列表
         */
        updateDetailItem: (state, action: PayloadAction<DetailItem[]>) => {
            state.detailItems = action.payload;
        }
    },
    extraReducers: (builder) => {
        builder.addCase(fetchReportDetailList.pending, (state, action) => {
            state.requestStatus = RequestStatus.PENDING;
            state.loading = true;
        });
        builder.addCase(fetchReportDetailList.rejected, (state, action) => {
            state.loading = false;
            state.requestStatus = RequestStatus.ERROR;
        });
        builder.addCase(fetchReportDetailList.fulfilled, (state, action) => {
            state.loading = false;
            state.requestStatus = RequestStatus.SUCCESS;
            const {success, data} = action.payload;
            if (success){
                state.data = data;
                const tempTotalAmount = data.reduce((total, item) => total + item.amount * AMOUNT_ACCURACY, 0);
                state.totalMoney = tempTotalAmount / AMOUNT_ACCURACY;
            }
        });
        builder.addCase(fetchAddReportDetail.fulfilled, (state, action) => {
            if (action.payload.success){
                state.data.unshift(action.payload.data);
                state.totalMoney = (state.totalMoney * AMOUNT_ACCURACY + action.payload.data.amount * AMOUNT_ACCURACY) / AMOUNT_ACCURACY;
            }
        });
        builder.addCase(fetchUpdateReportDetail.fulfilled, (state, action) => {
            if (action.payload.success){
                const { id, item, consumeDate, amount, remark } = action.payload.detail;
                state.data.forEach( e => {
                    if (e.id === id){
                        e.item = item;
                        e.consumeDate = consumeDate;
                        e.remark = remark;
                        if (e.amount !== amount){
                            const diff = e.amount * AMOUNT_ACCURACY - amount * AMOUNT_ACCURACY;
                            state.totalMoney = (state.totalMoney * AMOUNT_ACCURACY - diff) / AMOUNT_ACCURACY;
                            e.amount = amount;
                        }
                    }
                });
            }
        });
        builder.addCase(fetchDetailItemList.fulfilled, (state, action) => {
           if (action.payload.success){
               state.detailItems = action.payload.data;
               action.payload.data.forEach(e => {
                  if (e.defaultSelected){
                      state.defaultItem = e.label;
                      return;
                  }
               });
               if (action.payload.data.length === 0){
                   state.detailItems = [ { key: "have a meal", label: "default", show: true, defaultSelected: true} ];
               }
           }
        });
        builder.addCase(fetchRemoveItem.fulfilled, (state, action) => {
            const index = state.detailItems.findIndex(e => e.key === action.payload);
            if (index !== -1){
                state.detailItems.splice(index, 1);
            }
        });
    }
});

export const {updateReportId, updateDetailItem} = reportDetailSlice.actions;
export default reportDetailSlice.reducer;

